﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Albums;
using SIG.InputModel.Admin.Links;
using SIG.Model;
using SIG.Model.Albums;
using SIG.Model.Enums;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Albums;
using SIG.ViewModel.Admin.Links;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class PhotoController : BaseController
    {
        private readonly IPhotoService _photoService;
        private readonly IAlbumService _albumService;
        private readonly IMapper _mapper;

        public PhotoController(IPhotoService photoService, IAlbumService albumService, IMapper mapper)
        {
            _photoService = photoService;
            _albumService = albumService;
            _mapper = mapper;

        }
        // GET: Admin/Photo

        #region 分类

        public ActionResult Index(int? page, int albumId, string keyword)
        {
            PhotoListVM photoListVM = GetElements(page, albumId, keyword);

            photoListVM.Album = _albumService.GetById(albumId);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(photoListVM);
        }

        private PhotoListVM GetElements(int? page,int? albumId, string keyword)
        {
            var photoListVM = new PhotoListVM();
            photoListVM.AlbumId = albumId;
            photoListVM.Keyword = keyword;
            photoListVM.PageIndex = (page ?? 1) - 1;
            photoListVM.PageSize = SettingsManager.Link.PageSize;
            int totalCount;
            var photolist = _photoService.GetPagedElements(photoListVM.PageIndex, photoListVM.PageSize, photoListVM.Keyword, photoListVM.AlbumId, out totalCount);
            var specialistVMList = _mapper.Map<List<Photo>, List<PhotoVM>>(photolist);
            photoListVM.TotalCount = totalCount;
            photoListVM.Photos = new StaticPagedList<PhotoVM>(specialistVMList, photoListVM.PageIndex + 1, photoListVM.PageSize, photoListVM.TotalCount); ;
            return photoListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/PhotoSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add(int albumId)
        {
            var vPhoto = new PhotoIM
            {
                Active = true,
                Importance = 0,
                AlbumId = albumId
            };
           
            return PartialView("_Add", vPhoto);
        }



        [HttpPost]
        public JsonResult Add(PhotoIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newPhoto = _mapper.Map<PhotoIM, Photo>(vm);
            if (!string.IsNullOrEmpty(newPhoto.FullImageUrl))
            {
                var imgurl = HostingEnvironment.MapPath(newPhoto.FullImageUrl);
                var ext = System.IO.Path.GetExtension(imgurl).ToLower();
                var thumbName = System.IO.Path.GetFileName(imgurl);
                var thumDir = HostingEnvironment.MapPath(SettingsManager.Photo.ThumbDir);
                if (!System.IO.Directory.Exists(thumDir))
                {
                    System.IO.Directory.CreateDirectory(thumDir);
                }
                var thumbUrl = System.IO.Path.Combine(thumDir, thumbName);

                ImageHandler.MakeThumbnail(imgurl, thumbUrl, SettingsManager.Photo.ThumbWidth, SettingsManager.Photo.ThumbHeight, "Cut", ext);
                newPhoto.Thumbnail = $"{SettingsManager.Photo.ThumbDir}/{thumbName}";
            }

            _photoService.Create(newPhoto);

        
            int count;
            var pageSize = SettingsManager.Link.PageSize;
            var list = _photoService.GetPagedElements(0, pageSize, string.Empty, null, out count);
            List<PhotoVM> categories = _mapper.Map<List<Photo>, List<PhotoVM>>(list);
            AR.Data = RenderPartialViewToString("_PhotoList", categories);
      
            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Photo));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Photo photo = _photoService.GetById(id);
            if (photo == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }
            var vm = _mapper.Map<PhotoIM>(photo);
            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(PhotoIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            var oldPhoto = _photoService.GetById(vm.Id);

           
            if (oldPhoto.FullImageUrl != vm.FullImageUrl)
            {
                //var thumb = HostingEnvironment.MapPath(oldPhoto.Thumbnail);
                //if (System.IO.File.Exists(thumb))
                //{
                //    System.IO.File.Delete(thumb);
                //}

                var imgurl = HostingEnvironment.MapPath(vm.FullImageUrl);
                var ext = System.IO.Path.GetExtension(imgurl).ToLower();
                var thumbName = System.IO.Path.GetFileName(imgurl);
                var thumDir = HostingEnvironment.MapPath(SettingsManager.Photo.ThumbDir);
                if (!System.IO.Directory.Exists(thumDir))
                {
                    System.IO.Directory.CreateDirectory(thumDir);
                }
                var thumbUrl = System.IO.Path.Combine(thumDir, thumbName);

                ImageHandler.MakeThumbnail(imgurl, thumbUrl, SettingsManager.Photo.ThumbWidth, SettingsManager.Photo.ThumbHeight, "Cut", ext);
                oldPhoto.Thumbnail = $"{SettingsManager.Photo.ThumbDir}/{thumbName}";

            }
            oldPhoto.Importance = vm.Importance;
            oldPhoto.Title = vm.Title;
            oldPhoto.FullImageUrl = vm.FullImageUrl;
            oldPhoto.Active = vm.Active;
           
            _photoService.Update(oldPhoto);

            var photo = _mapper.Map<PhotoVM>(oldPhoto);
            AR.Id = photo.Id;
            AR.Data = RenderPartialViewToString("_PhotoItem", photo);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Photo));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Photo vPhoto = _photoService.GetById(id);

           
            _photoService.Delete(vPhoto);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Photo));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vPhoto = _photoService.GetById(id);
            if (vPhoto == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vPhoto.Active = !vPhoto.Active;
                _photoService.Update(vPhoto);
                var vm = _mapper.Map<PhotoVM>(vPhoto);

                AR.Data = RenderPartialViewToString("_PhotoItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Photo));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _photoService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}